<?php
/**
 * Notes:
 * User: LiaoHong
 * Date: 2025/10/24
 * Time: 10:17
 **/
namespace App\Services\Pull;

use App\Models\Archives\ArchivesAdmin;
use App\Models\Archives\ArchivesFile;
use App\Models\DownloadTasks;
use App\Models\Project\Folder;
use App\Models\Project\Project;
use Illuminate\Support\Facades\DB;
use \Exception;
class PullService
{
    /**
     * @Notes:获取项目设置
     * @return mixed
     * @author: Liao Hong
     * @Time: 2025/10/24   14:00
     * @Interface getSetting
     */
    public function getSetting($path='',$params = [],$method = 'GET'){
        $row = DB::table('pull_setting')->find(1);
        if(!$row){
            throw new Exception('请先设置拉取数据的基本信息，包括远程地址和系统类型！');
        }
        $row    = object_to_array($row);
        $type   = $row['type'];
        $url    = $row['site_url'].$path;
        $data   = httpRequest($url,$params,$method);
        if (!empty($data)) {
            $data = json_decode($data,true);
            if($data['code'] !== 200){
                throw new Exception('接口数据为空！');
            }
        }else{
            throw new Exception('接口请求失败！');
        }
        return [$type,$data];
    }
    /**
     * @Notes:获取项目列表
     * @param $params
     * @author: Liao Hong
     * @Time: 2025/10/24   10:20
     * @Interface receiveData
     */
    public function getProject(){
        $model = new Project();
        $isPull = $model->where('id','>=',1)->exists();
        if(!$isPull){
            $path = 'Archivistics/index';
            [$type,$data]     = $this->getSetting($path);
            $insertData = $data['data'];
            //老系统请求的数据直接入库
            if($type == 2){
                $row =$model->insert($model->filterMultipleFields($insertData));
            }else{
                //新系统请求的数据需要二次处理
                $row = true;
            }
            return $row;
        }else{
            throw new Exception('在该平台已拉取过项目数据，无需重复拉取！');
        }
    }

    /**
     * @Notes:获取文件夹信息
     * @param $params
     * @author: Liao Hong
     * @Time: 2025/10/24   14:40
     * @Interface getFolder
     */
    public function getFolder($params)
    {
        if(!isset($params['project_id']) || empty($params['project_id'])){
            throw new Exception('请传入项目id，项目id不能为空！');
        }
        $projectId = intval($params['project_id']);
        $model = new Folder();
        $isPull = $model->where('id','>=',1)->exists();
        if(!$isPull){
            $path = 'Archivistics/geTreeDatas';
            $params = [
                'project_id' =>$projectId
            ];
            [$type,$data]     = $this->getSetting($path,$params);
            $insertData = $data['data'];
            //老系统请求的数据直接入库
            DB::beginTransaction();
            try {
                if($type == 2){
                    foreach ($insertData as $v1){
                        $ins = [
                            'title'       => $v1['title'],
                            'type'        => $type,
                            'project_id'  => $projectId,
                            'number'      => $v1['number'],
                            'spread'      => isset($v1['children']) ? 1: 0,
                        ];
                        $add_1 = Folder::query()->insertGetId($ins);
                        if(isset($v1['children']) && !empty($v1['children'])){
                            foreach ($v1['children'] as $v2){
                                $ins= [
                                    'title'              => $v2['title'],
                                    'parent_id'          => $add_1,
                                    'type'               => $type,
                                    'project_id'         => $projectId,
                                    'number'             => $v2['number'],
                                    'contract_number'    => isset($v2['contract_number']) ? $v2['contract_number'] : '',
                                    'spread'             => isset($v2['spread']) ? $v2['spread'] ? 1: 0 : 0,
                                ];
                                Folder::query()->insert($ins);
                            }
                        }
                    }
                }else{
                    //新系统请求的数据需要二次处理
                    $row = true;
                }
                DB::commit();
                return true;
            }catch (Exception $exception){
                DB::rollBack();
                throw new Exception('添加文件夹失败！'.$exception->getMessage());
            }
        }else{
            throw new Exception('在该平台已拉取过文件夹数据，无需重复拉取！');
        }
    }

    /**
     * @Notes:获取案卷数据
     * @param $params
     * @author: Liao Hong
     * @Time: 2025/10/24   16:22
     * @Interface getFileList
     */
    public function getArchivesAdmin($params)
    {
        if(!isset($params['project_id']) || empty($params['project_id'])){
            throw new Exception('请传入项目id，项目id不能为空！');
        }
        $model = new ArchivesAdmin();
        $isPull = $model->where('id','>=',1)->exists();
        if(!$isPull){
            $path = 'Archivistics/getArchiveList';
            $params = [
                'project_id' => $params['project_id'],
                'reference'  => $params['reference'],
                'page'       => isset($params['page']) ? $params['page'] : 1,
                'limit'      => isset($params['limit']) ? $params['limit'] : 10,
            ];
            [$type,$data]     = $this->getSetting($path,$params,'POST');
            if ($type == 2){
                $insertData = $data['data']['data'];
                $insertData = array_map(function ($item) {
                    $item['final_big_file'] = isset($item['aurl']) ? $item['aurl'] : '';
                    unset($item['aurl']);
                    return $item;
                }, $insertData);
                $row =$model->insert($model->filterMultipleFields($insertData));
                if ($row) {
                    $taskData = [];
                    $tableName = $model->getTable();
                    foreach ($insertData as $item) {
                        // 处理xmlUrl字段
                        if (!empty($item['xmlUrl'])) {
                            $taskData[] = [
                                'table_name' => $tableName,
                                'download_url' => $item['xmlUrl'],
                                'created_at' => getTime()
                            ];
                        }
                        // 处理final_big_file字段
                        if (!empty($item['final_big_file'])) {
                            $taskData[] = [
                                'table_name' => $tableName,
                                'download_url' => $item['final_big_file'],
                                'created_at' => getTime()
                            ];
                        }
                    }
                    if (!empty($taskData)) {
                        DownloadTasks::query()->insert($taskData);
                    }
                }
            }else{
                $row = true;
            }
           return $row;
        }else{
            throw new Exception('在该平台已拉取过案卷数据，无需重复拉取！');
        }
    }

    /**
     * @Notes:获取卷内数据
     * @author: Liao Hong
     * @Time: 2025/10/24   17:25
     * @Interface getArchivesFile
     */
    public function getArchivesFile($params)
    {
        if(!isset($params['archives_id']) || empty($params['archives_id'])){
            throw new Exception('请传入案卷ID，案卷ID不能为空！');
        }
        $model = new ArchivesFile();
        $isPull = $model->where('id','>=',1)->exists();
        if(!$isPull){
            $path = 'Archivistics/indexLists';
            $params = ['id' => intval($params['archives_id'])];
            [$type,$data]     = $this->getSetting($path,$params,);
            if ($type == 2){
                $insertData = $data['data'];
                $row =$model->insert($model->filterMultipleFields($insertData));
                if ($row) {
                    $taskData = [];
                    $tableName = $model->getTable();
                    foreach ($insertData as $item) {
                        // 处理url字段
                        if (!empty($item['url'])) {
                            $taskData[] = [
                                'table_name' => $tableName,
                                'download_url' => $item['url'],
                                'created_at' => getTime()
                            ];
                        }
                        // 处理xmlUrl字段
                        if (!empty($item['xmlUrl'])) {
                            $taskData[] = [
                                'table_name' => $tableName,
                                'download_url' => $item['xmlUrl'],
                                'created_at' => getTime()
                            ];
                        }
                    }
                    if (!empty($taskData)) {
                        DownloadTasks::query()->insert($taskData);
                    }
                }

            }else{
                $row = true;
            }
            return $row;
        }else{
            throw new Exception('在该平台已拉取过该案卷的卷内数据，无需重复拉取！');
        }
    }
}
